package org.xbdframework.jdbc.core;

import java.util.Collection;
import java.util.Date;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;

public abstract class SqlParameterValueUtils {

	public final static String NULL_VALUE = "null";

	private SqlParameterValueUtils() {

	}

	public static String getValue(Object value) {
		if (value == null) {
			return NULL_VALUE;
		}
		if (value instanceof String) {
			return filterValue(value.toString());
		}
		else if (value instanceof Date) {
			return filterValue(value.toString());
		}
		else if (value.getClass().isArray()) {
			return Stream.of((Object[]) value).map(SqlParameterValueUtils::filterValue)
					.collect(Collectors.joining(", "));
		}
		else if (value instanceof Collection) {
			return ((Collection<Object>) value).stream()
					.map(SqlParameterValueUtils::filterValue)
					.collect(Collectors.joining(", "));
		}

		return value.toString();
	}

	public static String filterValue(Object value) {
		if (value instanceof String || value instanceof Date) {
			return filterValue(value.toString());
		}

		return value.toString();
	}

	public static String filterValue(String value) {
		return "'" + StringUtils.replace(value, "'", "''") + "'";
	}

}
